package org.openfdtd.gui.components;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

/**
 *
 * @author Dórian C. Langbeck
 */
public class PopupMenu extends JPopupMenu {

    public PopupMenu() {
        super();
    }

    public void add(String option, ActionListener action) {
        JMenuItem item = new JMenuItem(option);
        item.addActionListener(action);
        add(item);
    }

    public void addRotuleSeparator(String str) {
        new Rotule(this, str);
    }

    private static class Rotule extends JComponent {
        private String str;

        public Rotule(PopupMenu parent, String str) {
            this.str = str;
            parent.add(this);

            int w = getFontMetrics(getFont()).stringWidth(str) + 10;
            int pw = parent.getPreferredSize().width;
            
            setPreferredSize(new Dimension(
                Math.max(pw, w),
                getFontMetrics(getFont()).getHeight() + 5
            ));
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;

            g2d.setColor(Color.LIGHT_GRAY);
            g2d.setPaint(new GradientPaint(0, 0, Color.DARK_GRAY, 50, 0, Color.GRAY));
            g2d.fillRect(0, 0, getWidth(), getHeight());

            g2d.setColor(Color.WHITE);
            g2d.drawString(str, 5, g.getFontMetrics().getHeight());

            g2d.dispose();
        }
    }
}
